﻿// Controllers/AccountController.cs
using WebApplication1.Models;
using System.Linq;
using System.Web.Mvc;
using System;

namespace WebApplication1.Controllers
{
    public class AccountController : Controller
    {
        private ExamDbContext db = new ExamDbContext();

        // GET: 登录页面
        [HttpGet]
        public ActionResult Login()
        {
            // 临时取消自动跳转用于测试
            /*
            // 如果用户已经登录，直接跳转到相应页面
            if (Session["UserId"] != null)
            {
                System.Diagnostics.Debug.WriteLine($"用户已登录，Role: {Session["Role"]}");
                if (Session["Role"]?.ToString() == "Admin")
                {
                    System.Diagnostics.Debug.WriteLine("重定向到 Admin/Index");
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("重定向到 Employee/Index");
                    return RedirectToAction("Index", "Employee");
                }
            }
            */
            // 设置默认语言（如果还没有设置）

            System.Diagnostics.Debug.WriteLine("显示登录页面");

            return View();
        }

        // POST: 登录验证
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(string username, string password)
        {

            if (Session["Culture"] == null)
            {
                // 可以根据浏览器语言设置默认语言，或者设置为中文
                var browserLang = Request.UserLanguages?.FirstOrDefault();
                var defaultLang = "zh-CN"; // 默认中文

                if (!string.IsNullOrEmpty(browserLang))
                {
                    if (browserLang.StartsWith("vi", StringComparison.OrdinalIgnoreCase))
                    {
                        defaultLang = "vi-VN";
                    }
                }

                WebApplication1.Utilities.LanguageManager.SetCurrentLanguage(defaultLang);
            }

            // 验证输入
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                ViewBag.ErrorMessage = "请输入用户名和密码";
                return View();
            }

            var user = db.Users.FirstOrDefault(u => u.Username == username && u.Password == password);


            //// 临时模拟登录成功
            //Session["UserId"] = 1;
            //Session["Username"] = "admin";
            //Session["Role"] = "Admin";
            //Session["FullName"] = "系统管理员";

            //System.Diagnostics.Debug.WriteLine("模拟登录成功，重定向到 Admin/Index");
            //return RedirectToAction("Index", "Admin");


            if (user != null)
            {
                Session["UserId"] = user.UserId;
                Session["Username"] = user.Username;
                Session["Role"] = user.Role;
                Session["FullName"] = user.FullName;

                System.Diagnostics.Debug.WriteLine($"用户登录成功，Role: {user.Role}");

                //登录成功后跳转到对应角色的首页
                if (user.Role == "Admin")
                {
                    System.Diagnostics.Debug.WriteLine("重定向到 Admin/Index");
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("重定向到 Employee/Index");
                    return RedirectToAction("Index", "Employee");
                }
            }

            ViewBag.ErrorMessage = "用户名或密码错误";
            System.Diagnostics.Debug.WriteLine("登录失败，返回登录页面");
            return View();

        }

        // 注销
        public ActionResult Logout()
        {
            Session.Clear();
            return RedirectToAction("Login");
        }// Controllers/AccountController.cs
         // 在AccountController类中添加或更新以下方法

        // 修改密码页面
        [HttpGet]
        public ActionResult ChangePassword()
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("Login", "Account");
            }

            return View();
        }

        // 处理修改密码
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (ModelState.IsValid)
            {
                var userId = (int)Session["UserId"];
                var user = db.Users.Find(userId);

                if (user == null)
                {
                    ModelState.AddModelError("", "用户不存在。");
                    return View(model);
                }

                // 验证当前密码
                if (user.Password != model.OldPassword)
                {
                    ModelState.AddModelError("OldPassword", "当前密码不正确。");
                    return View(model);
                }

                // 验证新密码和确认密码是否一致
                if (model.NewPassword != model.ConfirmPassword)
                {
                    ModelState.AddModelError("ConfirmPassword", "新密码和确认密码不一致。");
                    return View(model);
                }

                // 更新密码
                user.Password = model.NewPassword;
                db.Entry(user).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                TempData["SuccessMessage"] = "密码修改成功！";
                return RedirectToAction("ChangePassword");
            }

            return View(model);
        }

        public ActionResult DeleteExam(int id)
        {
            return View();
        }
        public ActionResult DeleteExam1(int id)
        {
            return View();
        }
    }
}